package com.alili_tv.system.service.impl;

import com.alili_tv.system.entity.Video;
import com.alili_tv.system.entity.VideoTag;
import com.alili_tv.system.mapper.VideoMapper;
import com.alili_tv.system.service.TagService;
import com.alili_tv.system.service.VideoService;
import com.alili_tv.system.service.VideoTagService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.BaseAnalysis;
import org.springframework.stereotype.Service;
import org.w3c.dom.Text;

import java.util.*;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 视频/合集表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2023-03-17
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Resource
    private VideoMapper videoMapper;

    @Resource
    private TagService tagService;

    @Resource
    private VideoTagService videoTagService;

    @Override
    public boolean hasNew(long userId) {
        return videoMapper.hasNew(userId);
    }

    @Override
    public List<Video> getRecommend(int count, Integer channelId) {
        // select * from video order by rand() limit 6;
        return videoMapper.getRecommend(count, channelId);
    }

    @Override
    public List<Video> getOrderByIn(Collection<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        return videoMapper.getOrderByIn(ids);
    }

    @Override
    public Integer getChannelById(long videoId) {
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(Video::getChannel)
                .eq(Video::getId, videoId);
        Video one = this.getOne(queryWrapper);
        return one == null ? null : one.getChannel();
    }

    @Override
    public List<Video> getDynamic(long userId, int pageIndex, int pageSize) {
        return videoMapper.getDynamic(userId, pageIndex, pageSize);
    }

    @Override
    public Map<Long, Video> getByIds(Collection<Long> ids) {
        return videoMapper.getByIds(ids);
    }


    @Override
    public List<Video> searchVideos(String content, Integer sort, Integer time, Integer channel) {
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();

        // 通过tag获取视频ids
        Set<Long> videoIds = searchByTag(content);

        // select * from video where id in (videoids) or title like #{content}
        queryWrapper.and(qw1 -> {
            qw1.in(videoIds != null && videoIds.size() > 0, Video::getId, videoIds);
            qw1.or(qw2 -> qw2.like(Video::getTitle, content));
        });

        // 其他条件拼接
        queryWrapper.eq(channel != 1, Video::getChannel, channel);
        switch (time) {
            case 1 -> {
            }
            case 2 -> queryWrapper.le(Video::getTotalTime, 10 * 60);
            case 3 -> queryWrapper.between(Video::getTotalTime, 10 * 60, 30 * 60);
            case 4 -> queryWrapper.between(Video::getTotalTime, 30 * 60, 60 * 60);
            default -> queryWrapper.ge(Video::getTotalTime, 60 * 60);
        }
        queryWrapper.orderByDesc(sort == 1, Video::getViewCount);
        queryWrapper.orderByDesc(sort != 1, Video::getCreateTime);

        return this.list(queryWrapper);
    }

    /**
     * 查询视频id
     * @param text
     * @return
     */
    private Set<Long> searchByTag(String text) {
        // 查询tagIds
        List<Long> tagIds = tagService.searchTag(text);
        if (tagIds == null || tagIds.size() == 0) {
            return null;
        }
        // 通过tagId获取视频id
        LambdaQueryWrapper<VideoTag> queryWrapper = new LambdaQueryWrapper<VideoTag>()
                .select(VideoTag::getVideoId)
                .in(VideoTag::getTagId, tagIds);
        List<VideoTag> videoTags = videoTagService.list(queryWrapper);
        return videoTags.stream().map(VideoTag::getVideoId).collect(Collectors.toSet());
    }


    /**
     * # 标题
     * : tag
     * {} 且
     * [] 或
     * , 分隔符
     *
     * @param content
     * @param sort    1：最多点击 2：最新发布
     * @param time    1：全部时长 2：10分钟以下 3：10-30分钟 4：30-60分钟 5：60分钟以上
     * @param channel 1：全部分区 else：分区id
     */
//    @Override
//    public List<Video> searchVideos(String content, Integer sort, Integer time, Integer channel) {
//        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
//        // 判断是否使用精准查询
//        if (hasFlags(content)) {
//
//        } else {
//            queryWrapper.like(Video::getTitle, content);
//        }
//
//        // 其他条件拼接
//        queryWrapper.eq(channel != 1, Video::getChannel, channel);
//        switch (time) {
//            case 1 -> {
//            }
//            case 2 -> queryWrapper.le(Video::getTotalTime, 10 * 60);
//            case 3 -> queryWrapper.between(Video::getTotalTime, 10 * 60, 30 * 60);
//            case 4 -> queryWrapper.between(Video::getTotalTime, 30 * 60, 60 * 60);
//            default -> queryWrapper.ge(Video::getTotalTime, 60 * 60);
//        }
//        queryWrapper.orderByDesc(sort == 1, Video::getViewCount);
//        queryWrapper.orderByDesc(sort != 1, Video::getCreateTime);
//
//        return this.list(queryWrapper);
//    }

    // [vue,vue3]
    private void calculateQueryMapper(String content, LambdaQueryWrapper<Video> queryWrapper) {

    }

    private boolean hasFlags(String str) {
        Pattern pattern = Pattern.compile("[#:：\\[(]");
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

}
